<template>
  <div class="tinymce-editor">
    <editor :id="editorId" v-model="content" :init="initConfig" />
  </div>
</template>
<script>
import { getOssKey } from '@utils/countDownload'
import Editor from '@tinymce/tinymce-vue'
const fontFormats = `
      微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;宋体=simsun,serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;Arial=arial,helvetica,sans-serif;
      Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;
      Georgia=georgia,palatino;Helvetica=helvetica;Verdana=verdana,geneva;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;
      Times New Roman=times new roman,times;
    `
const plugins = [
  `advlist autolink lists link image charmap print preview anchor,searchreplace visualblocks code fullscreen, insertdatetime media paste wordcount image`
]
const toolbar = [
  `code | fontselect fontsizeselect | undo redo | cut copy paste | bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify | image media`,
  `formatselect | bullist numlist outdent indent | removeformat | fullscreen preview`
]
export default {
  name: 'TinyMce',
  components: {
    editor: Editor
  },
  props: {
    editorId: {
      type: String,
      default: function() {
        return `${new Date().getTime()}tinymce`
      }
    },
    editorHeight: {
      type: Number,
      default: function() {
        return 600
      }
    },
    editorContent: {
      type: String,
      default: function() {
        return ''
      }
    },
    imgSize: {
      type: Number,
      default: function() {
        return 10
      }
    },
    mediaSize: {
      type: Number,
      default: function() {
        return 200
      }
    },
    imgAccept: {
      type: String,
      default: function() {
        return '.jpg, .jpeg, .png, .gif'
      }
    },
    mediaAccept: {
      type: String,
      default: function() {
        return '.mp4'
      }
    },
    textMax: {
      type: Number,
      default: function() {
        return 2000
      }
    }
  },
  watch: {
    editorContent: {
      handler(newVal) {
        this.content = newVal
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      content: '',
      nowLength: 0,
      initConfig: {
        plugins,
        toolbar,
        branding: false,
        language: 'zh_CN',
        font_formats: fontFormats,
        height: this.editorHeight,
        content_style: 'p,h1,h2,h3,h4,h5,h6,div,pre {margin: 0px};',
        file_picker_callback: (callback, value, meta) => {
          const _this = this
          let filetype = ''
          let materialType = ''
          switch (meta.filetype) {
            case 'image':
              filetype = _this.imgAccept
              materialType = '1'
              break
            case 'media':
              filetype = _this.mediaAccept
              break
          }
          let input = document.createElement('input')
          input.setAttribute('type', 'file')
          input.setAttribute('accept', filetype)
          input.click()
          input.onchange = function() {
            let file = this.files[0]
            const fileSize = file.size / 1024 / 1024
            const fileSuffix = file.name.substring(file.name.lastIndexOf('.'))
            if (materialType == '1') {
              if (_this.imgAccept.indexOf(fileSuffix) === -1) {
                _this.$message.warning(`只支持上传${_this.imgAccept}类型的图片`)
                return
              }
              if (fileSize > _this.imgSize) {
                _this.$message.warning(
                  `图片最大限制为${_this.imgSize}M,当前图片大小${fileSize}M`
                )
                return
              }
              _this.uploadOss(file, ({ url, fileName }) => {
                callback(url, { title: fileName })
              })
            } else {
              if (_this.mediaAccept.indexOf(fileSuffix) === -1) {
                _this.$message.warning(
                  `只支持上传${_this.mediaAccept}类型的媒体文件`
                )
                return
              }
              if (fileSize > _this.mediaSize) {
                _this.$message.warning(
                  `媒体文件最大限制为${_this.mediaSize}M,当前媒体文件大小${fileSize}M`
                )
                return
              }
              _this.uploadOss(file, ({ url, fileName }) => {
                callback(url, { title: fileName })
              })
            }
          }
        },
        init_instance_callback: function(editor) {
          $(editor.getContainer())
            .find('button.tox-statusbar__wordcount')
            .click()
        }
      }
    }
  },
  methods: {
    /* 上传OSS */
    uploadOss(file, sucBack) {
      let loading = this.$loading({
        lock: true,
        text: '上传中……',
        background: 'rgba(0, 0, 0, 0.7)',
        target: 'tox-dialog'
      })
      const bucketName =
        process.env.VUE_APP_ENV === 'testENV'
          ? 'dapeng-test-image'
          : 'dapeng-image'
      const date = this.moment(new Date().getTime()).format('YYYY-MM-DD')
      const userId = this.$store.state.user.dapengUserId
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.'))
      getOssKey({}, (res) => {
        const client = new OSS({
          // yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
          region: 'oss-cn-beijing',
          // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
          accessKeyId: res.accessKeyId,
          accessKeySecret: res.accessKeySecret,
          // 从STS服务获取的安全令牌（SecurityToken）。
          stsToken: res.securityToken,
          // 填写Bucket名称。
          bucket: bucketName
        })
        const uploadUrl = `${date}/${userId}/${new Date().getTime()}_T1BFUkFURQ==${fileSuffix}`
        async function put() {
          try {
            await client.put(uploadUrl, file)
            const url = `${process.env.VUE_APP_OSS_URL}${uploadUrl}`
            sucBack({ url, uploadUrl })
            loading.close()
          } catch (e) {
            _this.$message.error('上传失败')
            loading.close()
          }
        }
        put()
      })
    },
    tinymceEditorContent(type) {
      this.nowLength = parseInt(
        document.getElementsByClassName('tox-statusbar__wordcount')[0].innerHTML
      )
      if (type === 'other') {
        if (!this.nowLength) return { content: '', flag: false }
        if (this.nowLength > this.textMax)
          return { content: this.content, flag: false }
        return { content: this.content, flag: true }
      } else {
        if (!this.nowLength) return ''
        if (this.nowLength > this.textMax) {
          this.$message.warning(
            `超出最大字数限制,最大${this.textMax}个字符,当前${this.nowLength}个字符`
          )
          return false
        }
        return this.content
      }
    }
  }
}
</script>
<style lang="less">
.tox-tinymce-aux {
  z-index: 3000 !important;
}
.el-loading-mask {
  z-index: 3000 !important;
}
.tox-notifications-container {
  display: none;
}
</style>
